<?php

namespace app\api\controller;

use app\api\exception\ApiException;
use app\common\constant\ErrorCode;
use app\middleware\JwtAuthMiddleware;
use app\service\JwtService;

/**
 * 用户控制器
 */
class User extends Base
{
    /**
     * 获取用户信息
     */
    public function info()
    {
        try {
            $userInfo = $this->getUserInfo();
            
            if (empty($userInfo)) {
                throw new ApiException(
                    ErrorCode::getMessage(ErrorCode::AUTH_LOGIN_REQUIRED),
                    ErrorCode::AUTH_LOGIN_REQUIRED,
                    401
                );
            }

            // 获取Token统计信息
            $tokenStats = JwtService::getTokenStats($this->token);
            
            $result = [
                'user_info' => $userInfo,
                'token_info' => $tokenStats,
                'online_status' => JwtAuthMiddleware::getUserOnlineStatus($this->getUserId()),
            ];
            
            return $this->success($result);

        } catch (ApiException $e) {
            throw $e;
        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    /**
     * 用户登出
     */
    public function logout()
    {
        try {
            if (empty($this->token)) {
                throw new ApiException(
                    '未找到有效的登录状态',
                    ErrorCode::AUTH_TOKEN_MISSING,
                    400
                );
            }

            // 将Token加入黑名单
            JwtAuthMiddleware::logout($this->token);
            
            $this->logOperation('user_logout');
            
            return $this->success([], '退出登录成功');

        } catch (ApiException $e) {
            throw $e;
        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    /**
     * 获取在线状态
     */
    public function onlineStatus()
    {
        try {
            $userId = $this->getUserId();
            $onlineStatus = JwtAuthMiddleware::getUserOnlineStatus($userId);
            
            $result = [
                'user_id' => $userId,
                'is_online' => !empty($onlineStatus),
                'last_active' => $onlineStatus['last_active'] ?? 0,
                'last_active_text' => $onlineStatus ? date('Y-m-d H:i:s', $onlineStatus['last_active']) : '',
                'ip' => $onlineStatus['ip'] ?? '',
                'user_agent' => $onlineStatus['user_agent'] ?? '',
            ];
            
            return $this->success($result);

        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    /**
     * 刷新Token
     */
    public function refreshToken()
    {
        try {
            $refreshToken = $this->request->param('refresh_token', '');
            
            if (empty($refreshToken)) {
                throw new ApiException(
                    '刷新Token不能为空',
                    ErrorCode::PARAM_MISSING,
                    400
                );
            }

            $result = JwtService::refreshToken($refreshToken);
            
            $this->logOperation('token_refresh');
            
            return $this->success($result, 'Token刷新成功');

        } catch (ApiException $e) {
            throw $e;
        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    /**
     * 修改用户信息
     */
    public function updateProfile()
    {
        try {
            $data = $this->validateParams([
                'nickname' => 'max:50',
                'avatar' => 'url|max:255',
                'mobile' => 'mobile',
                'email' => 'email',
            ], [
                'nickname.max' => '昵称长度不能超过50个字符',
                'avatar.url' => '头像必须是有效的URL',
                'avatar.max' => '头像URL长度不能超过255个字符',
                'mobile.mobile' => '手机号格式不正确',
                'email.email' => '邮箱格式不正确',
            ]);

            // 这里应该调用用户服务更新用户信息
            // $userService = new UserService();
            // $result = $userService->updateProfile($this->getUserId(), $data);
            
            $this->logOperation('update_profile', $data);
            
            return $this->success([], '用户信息更新成功');

        } catch (ApiException $e) {
            throw $e;
        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    /**
     * 获取用户操作日志
     */
    public function operationLogs()
    {
        try {
            [$page, $pageSize] = $this->getPaginationParams();
            
            $params = [
                'user_id' => $this->getUserId(),
                'page' => $page,
                'page_size' => $pageSize,
                'start_time' => $this->request->param('start_time', ''),
                'end_time' => $this->request->param('end_time', ''),
                'action' => $this->request->param('action', ''),
            ];

            // 这里应该调用日志服务获取操作日志
            // $logService = new OperationLogService();
            // $result = $logService->getUserLogs($params);
            
            $result = [
                'data' => [],
                'total' => 0,
                'page' => $page,
                'page_size' => $pageSize,
            ];
            
            return $this->paginate(
                $result['data'],
                $result['total'],
                $result['page'],
                $result['page_size']
            );

        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    /**
     * 检查Token状态
     */
    public function checkToken()
    {
        try {
            $token = $this->request->param('token', $this->token);
            
            if (empty($token)) {
                throw new ApiException(
                    'Token不能为空',
                    ErrorCode::PARAM_MISSING,
                    400
                );
            }

            $stats = JwtService::getTokenStats($token);
            
            return $this->success($stats);

        } catch (ApiException $e) {
            throw $e;
        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }
}
